package com.pmmaster.common.utils;

import javax.servlet.http.HttpServletRequest;

public class CommonUtil {
    /**
     * 去掉IP字符串前后所有的空格
     *
     * @param ip ip地址
     * @return 处理后的ip地址
     */
    public static String trimSpaces(String ip) {
        String ipAddress = ip;
        while (ipAddress.startsWith(" ")) {
            ipAddress = ipAddress.substring(1, ipAddress.length()).trim();
        }
        while (ipAddress.endsWith(" ")) {
            ipAddress = ipAddress.substring(0, ipAddress.length() - 1).trim();
        }
        return ipAddress;
    }

    /**
     * 判断是否是一个ip
     *
     * @param ip 待判读的ip地址
     * @return 是ip地址就返回true，否则返回false
     */
    public static boolean isIp(String ip) {
        String ipAddress = ip;
        boolean b = false;
        ipAddress = trimSpaces(ipAddress);
        if (ipAddress.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
            String[] s = ipAddress.split("\\.");
            if (Integer.parseInt(s[0]) < 255) {
                if (Integer.parseInt(s[1]) < 255) {
                    if (Integer.parseInt(s[2]) < 255) {
                        if (Integer.parseInt(s[3]) < 255) {
                            b = true;
                        }
                    }
                }
            }
        }
        return b;
    }

    /**
     * 获取ip地址
     *
     * @param request httpservlet请求
     * @return String ip地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            java.net.InetAddress addr = null;
            try {
                addr = java.net.InetAddress.getLocalHost();
                if (null != addr) {
                    ip = StringUtil.null2String(addr.getHostAddress()); // 获得本机IP
                }
            } catch (java.net.UnknownHostException e) {
                e.printStackTrace();
            }
        }
        if (ip != null && !"unknown".equalsIgnoreCase(ip) && !isIp(ip)) {
            String[] ips = ip.split(",");
            if (ips.length > 0) {
                ip = ips[0];
            }
        }
        return ip;
    }
}

